const redisClient = require('../redis/client');

const cacheMiddleware = (duration = 3600) => {
  return async (req, res, next) => {
    // 只缓存 GET 请求
    if (req.method !== 'GET') {
      return next();
    }

    const key = `cache:${req.originalUrl}`;

    try {
      // 检查缓存
      const cachedData = await redisClient.get(key);
      
      if (cachedData) {
        console.log('Serving from cache:', key);
        return res.json({
          source: 'cache',
          data: cachedData
        });
      }

      // 缓存未命中，继续处理请求
      const originalSend = res.json;
      res.json = function(data) {
        // 缓存响应数据
        redisClient.set(key, data, duration)
          .then(() => console.log('Data cached:', key))
          .catch(err => console.error('Cache set error:', err));

        // 恢复原始方法
        res.json = originalSend;
        return res.json({
          source: 'database',
          data: data
        });
      };

      next();
    } catch (error) {
      console.error('Cache middleware error:', error);
      next();
    }
  };
};

module.exports = cacheMiddleware;